/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import controllers.UserFacade;
import entities.User;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.codec.digest.DigestUtils;

/**
 *
 * @author selam
 */
@ManagedBean
@RequestScoped
@Named(value = "registration")

public class Registration {

    private User user;
    private String ID;
    private boolean logged;

    public boolean isLogged() {
        boolean logged;
        try {
            FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName();
            logged=true;
        } catch (Exception e) {
            logged=false;
        }
        return logged;
    }

    public void setLogged(boolean logged) {
        this.logged = logged;
    }
    
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public UserFacade getEao() {
        return eao;
    }

    public void setEao(UserFacade eao) {
        this.eao = eao;
    }
    @Inject
    private UserFacade eao;

    /**
     * Creates a new instance of Registration
     */
    public Registration() {
        user = new User();
    }

    public String register() {
        int j = (int) Math.random()*1000000000;
        System.out.println(j);
        user.setUserId(FacesContext.getCurrentInstance().hashCode());
        user.setRole("USER");  
        user.setPassword(DigestUtils.sha512Hex(user.getPassword()));
        eao.create(user);
        return "/faces/success.xhtml";
    }
    
    public String logout() {
        System.out.println("hello nice");
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        return "/faces/index.xhtml?faces-redirect=true";
    }
    
    
    public String getEmail() {
        String a = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName();
        return a;
    }
    
    public String getID() {
        String ret;
        try {
            ret = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName();
            this.logged=true;
        } catch (Exception e) {
            ret = "not logged";
            this.logged=false;
        }
        return ret;
    }

}
